$(function () {
    var initialLocaleCode = 'zh-cn';
    // var newEventFlag = false;
    var newEventFlag = true;

    function getHolidayEvents(holidays, color) {
        var events = [];
        for (var key in holidays) {
            events.push(
                {
                    "color": color,
                    "start": key,
                    "manhour": 0,
                    "remark": '',
                    "title": holidays[key]
                }
            );
        }
        return events;

    }

    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function isHolidaysOffset(d) {
        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var date = d.getDate();
        var result = typeof (holidaysOffset[[year, pad(month, 2), pad(date, 2)].join('-')]) != 'undefined'
        return result;
    }

    function isNotHoliday(d) {
        var year = d.getFullYear();
        var month = d.getMonth() + 1;
        var date = d.getDate();
        var result = typeof (holidays[[year, pad(month, 2), pad(date, 2)].join('-')]) === 'undefined'
        return result;
    }

    function isHoliday(d) {
        var weekDay = d.getDay();
        if (weekDay != 0 && weekDay != 6 && isNotHoliday(d)) {
            return false;
        } else {
            if (isHolidaysOffset(d)) {
                return false;
            } else {
                return true;
            }

        }
    }

    function getWorkingDays(startDate, endDate) {
        var result = 0;
        var currentDate = startDate;
        while (currentDate < endDate) {
            var weekDay = currentDate.getDay();
            if (weekDay != 0 && weekDay != 6) {
                if (isNotHoliday(currentDate)) {
                    result++;
                }
            } else {
                if (isHolidaysOffset(currentDate)) {
                    result++;
                }
            }
            currentDate.setDate(currentDate.getDate() + 1);
        }
        return result;
    }


    // 配置fullCalendar
    $('#calendar').fullCalendar({
        header: {
            left: 'prev,today,next',
            center: 'title',
            right: 'month,listMonth'
        },

        // listDayFormat: 'D MMMM YYYY',
        // listDayFormat: false,
        listDayAltFormat: false,
        firstDay: 1,

        // defaultDate: '2018-10-12',
        locale: initialLocaleCode,

        showNonCurrentDates: false,
        buttonIcons: false,
        editable: false,
        draggable: false,
        weekNumbers: true,
        navLinks: false, // 禁止通过点击日期到日视图
        selectable: true,
        selectHelper: false,
        eventLimit: true, // allow "more" link when too many events

        eventTextColor: '#000000',


        // 显示每日事件
        // 异步获取月事件，自带起始日期
        eventSources: [
            // 假日
            {
                events: getHolidayEvents(holidays, "#1ef8ff")
            },
            // 补班
            {
                events: getHolidayEvents(holidaysOffset, "#4b97ff")
            },
            // 正常工日
            {
                url: 'ajaxs/events',
                error: function () {
                    $('#script-warning').show();
                }
            }



        ],

        // 日程
        eventRender: function (event, element, view) {
            // $(element).find(".fc-list-item-title").after('<td class="fc-list-item-title fc-widget-content"><a>' + event.remark + '</a></td>');
            $(element).find(".fc-list-item-title").prepend('<a style="margin-left: 30px; " >' + event.manhour + 'h   </a>').append('<a style="margin-left: 30px; " >' + event.remark + '</a>');
        },

        // 单击日期创建新事件
        dayClick: function (date, jsEvent, view) {
            if (newEventFlag) {
                $('#tasktime').val(date.format('MM/DD/YYYY'));
                $('#manhour').val(date.manhour);
                $('#title').val(date.title);
                $('#remark').val(date.remark);
                $('#newevent-modal').modal();
                // $('#calendarModal').modal();
                // console.log(date.format('YYYY-MM-DD'),"new event");
            }
        },


        // 单击事件 修改/删除
        eventClick: function (calEvent, jsEvent, view) {
            if (newEventFlag) {

                $('#jobnumber2 option[value=' + calEvent.jobnumberid + ']').prop("selected", true);
                $('.selectpicker').selectpicker('refresh');
                $('#category2 option[value=' + calEvent.categoryid + ']').prop("selected", true);
                var subcategories, category, options;
                category = $('#category2 option[value=' + calEvent.categoryid + ']').html();
                subcategories = $('#subcategory3').html();
                options = $(subcategories).filter("optgroup[label='" + category + "']").html();
                if (options) {
                    $('#subcategory2').html(options);
                } else {
                    $('#subcategory2').empty();
                }
                $('#subcategory2 option[value=' + calEvent.subcategoryid + ']').prop("selected", true);

                $('#tasktime2').val(calEvent.start.format('MM/DD/YYYY'));
                $('#manhour2').val(calEvent.manhour);
                $('#title2').val(calEvent.title);
                $('#remark2').val(calEvent.remark);
                $('#taskid').val(calEvent.id);

                $('#editevent-modal').modal();
            }

        },


        // 显示每日工时总和
        eventAfterAllRender: function (view) {
            var start = view.start.format('YYYY-MM-DD');
            var end = view.end.format('YYYY-MM-DD');
            var overwork = 0;
            var normwork = 0;
            $('#manhourSummary').empty();
            $.ajax({
                url: 'ajaxs/count?start=' + start + '&end=' + end,
                success: function (data) {
                    for (cDay = view.start.clone(); cDay.isBefore(view.end); cDay.add(1, 'day')) {
                        var dateNum = cDay.format('YYYY-MM-DD');
                        var dayEl = $('.fc-day[data-date="' + dateNum + '"]');
                        var d = new Date(dateNum);

                        var countText = '';

                        var count = data['task'][dateNum];
                        if (count == null) {
                            count = '0';
                            countText = '0';
                        };


                        var color = 'White';
                        var i = parseFloat(count);
                        if (i <= 0) {
                            color = 'White';
                            countText = '0';
                        } else if (i <= 8) {
                            color = 'Green';
                            countText = count.toString();
                            if (isHoliday(d)) {
                                overwork += i;
                            } else {
                                normwork += i;
                            }
                        } else {
                            color = 'Red';
                            countText = '8 + ' + (i - 8).toFixed(1).toString();
                            if (isHoliday(d)) {
                                overwork += i;
                            } else {
                                normwork += 8;
                                overwork = overwork + (i - 8);
                            }
                        }

                        var html = '<span class="event-count" style="color:' + color + '">' +
                            '<i>' +
                            countText +
                            '</i>' +
                            '</span>';

                        dayEl.empty();
                        dayEl.append(html);
                    }

                    // 需要处理的问题
                    // 1 周末假日加班与正常上班工时分离。
                    // 2 添加休假类型统计

                    if (normwork > 0) {
                        $('#manhourSummary').append('<span class="label label-success">上班:' + normwork.toString() + '小时;</span>');
                    }

                    if (overwork > 0) {
                        $('#manhourSummary').append('<span class="label label-danger">加班:' + overwork.toString() + '小时;</span>');
                    }

                    for (var key in data['vacation']) {
                        $('#manhourSummary').append('<span class="label label-default">' + key + ':' + data['vacation'][key] + '小时;</span>');

                    }
                }
            });

            var begin = new Date(start);
            var end = new Date(end);
            var workingDays = getWorkingDays(begin, end)
            $('#manhourSummary').append('<span class="label label-primary">标准:' + workingDays * 8 + '小时(' + workingDays + '天);</span>');


        }
    });


    //// when the selected option changes, dynamically change the calendar option
    //$('#locale-selector').on('change', function () {
    //    if (this.value) {
    //        $('#calendar').fullCalendar('option', 'locale', this.value);
    //    }
    //});


    //// 是否创建新事件按钮 默认关闭
    //$('#toggle-event').bootstrapToggle('off');

    //$(function () {
    //    $('#toggle-event').change(function () {
    //        if ($(this).prop('checked')) {
    //            newEventFlag = true;
    //        } else {
    //            newEventFlag = false;
    //        }
    //    });
    //});

    // new event
    $(function () {
        var neweventform = $("#newevent-form");
        neweventform.bootstrapValidator({
            message: '输入值不合法',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                manhour: {
                    message: '工时不合法',
                    validators: {
                        notEmpty: {
                            message: '工时不能为空'
                        },
                        regexp: {
                            regexp: /^[0-9]+\.{0,1}[0-9]{0,5}$/,
                            message: '工时只能是数字'
                        }
                    }
                },
                title: {
                    validators: {
                        notEmpty: {
                            message: '任务不能为空'
                        }
                    }
                },
                jobnumberid: {
                    validators: {
                        notEmpty: {
                            message: '工作令号不能为空'
                        }
                    }
                },
                categoryid: {
                    validators: {
                        notEmpty: {
                            message: '大类不能为空'
                        }
                    }
                },
                subcategoryid: {
                    validators: {
                        notEmpty: {
                            message: '分类不能为空'
                        }
                    }
                }
            }
        });
        $("#newevent-submit").click(function () {
            var bv = neweventform.data('bootstrapValidator');
            bv.validate();
            if (bv.isValid()) {
                // console.log($("#newevent-form").serialize());
                $.ajax({
                    url: 'task',
                    async: false,//同步，会阻塞操作
                    type: 'POST',//PUT DELETE POST
                    data: neweventform.serialize(),
                    success: function (result) {
                        $('#newevent-modal').modal('toggle');
                        $('#calendar').fullCalendar('refetchEvents');
                        //console.log(result);
                    },
                    error: function () {
                    }
                });
            }
        });
    });


    // edit event
    $(function () {
        var editeventform = $("#editevent-form");
        editeventform.bootstrapValidator({
            message: '输入值不合法',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                manhour: {
                    message: '工时不合法',
                    validators: {
                        notEmpty: {
                            message: '工时不能为空'
                        },
                        regexp: {
                            regexp: /^[0-9]+\.{0,1}[0-9]{0,5}$/,
                            message: '工时只能是数字'
                        }
                    }
                },
                title: {
                    validators: {
                        notEmpty: {
                            message: '任务不能为空'
                        }
                    }
                },
                jobnumberid: {
                    validators: {
                        notEmpty: {
                            message: '工作令号不能为空'
                        }
                    }
                },
                categoryid: {
                    validators: {
                        notEmpty: {
                            message: '大类不能为空'
                        }
                    }
                },
                subcategoryid: {
                    validators: {
                        notEmpty: {
                            message: '分类不能为空'
                        }
                    }
                }
            }
        });
        $("#editevent-submit").click(function () {
            var bv = editeventform.data('bootstrapValidator');
            bv.validate();
            if (bv.isValid()) {
                var taskid = $("#taskid").val();
                // console.log($("#editevent-form").serialize());
                $.ajax({
                    url: 'task/' + taskid,
                    async: false,//同步，会阻塞操作
                    type: 'POST',//PUT DELETE POST
                    data: editeventform.serialize(),
                    success: function (result) {
                        $('#editevent-modal').modal('toggle');
                        $('#calendar').fullCalendar('refetchEvents');
                        //console.log(result);
                    },
                    error: function () {
                    }
                });
            }
        });
    });


    // delete event
    $(function () {
        $("#deleteevent-submit").click(function () {
            var taskid = $("#taskid").val();
            $.ajax({
                url: 'task/' + taskid + '/delete',
                async: false,//同步，会阻塞操作
                type: 'GET',//PUT DELETE POST
                success: function (result) {
                    $('#editevent-modal').modal('toggle');
                    $('#calendar').fullCalendar('refetchEvents');
                    //console.log(result);
                },
                error: function () {
                }
            });
        });
    });







});
